#import packages
from Basics.Detect_Shape import ShapeDetector
from Basics.Detect_Color import Colordetector
import argparse
import imutils
import cv2

#construct argument parse
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to the input image")
args = vars(ap.parse_args())

#load image, resize it
image = cv2.imread(args["image"])
resized = imutils.resize(image, width=300)
#ratio will be used to reset the coordinates from the resized one
ratio = image.shape[0] / float(resized.shape[0])

#initially process the image by blur gray threshhold cvt2LAB
blurred = cv2.GaussianBlur(resized, (5,5), 0)
gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)
lab = cv2.cvtColor(blurred, cv2.COLOR_BGR2LAB)
thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)[1]
# plan1 is 200 test good andif lower than 200 black  higher white INV is the opposite
#cv2.imshow("midd1", lab)
#cv2.waitKey(0)
#cv2.imshow("midd2", thresh)
#cv2.waitKey(0)
#find contours
cnts = cv2.findContours(thresh.copy(), 
						cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

#initialize shape and color detector
sd = ShapeDetector()
cl = Colordetector()

#loop & process the contours
for c in cnts:
	#compute the center of the contour
	M = cv2.moments(c)
	cX = int(M["m10"] / M["m00"] * ratio)
	cY = int(M["m01"] / M["m00"] * ratio)
	
	#detect the shape&color
	shape = sd.detect(c)
	color = cl.label(lab, c)
	
	#reset the coordinates using ratio & output results
	c = c.astype("float")
	c *= ratio 
	c = c.astype("int")
	text = "edcnt:{} clr:{}".format(shape, color)
	cv2.drawContours(image, [c], -1, (0,255,0), 2)
	cv2.putText(image, text, (cX-85,cY), 
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1)
	cv2.imshow("Result", image)
	cv2.waitKey(0)
	

	
